package com.ruimei.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

public class JsonTypeHandler<T>
  extends BaseTypeHandler<T>
{
  private static final Log log = LogFactory.getLog(JsonTypeHandler.class);
  private static ObjectMapper objectMapper = new ObjectMapper();
  private Class<T> type;
  
  public JsonTypeHandler(Class<T> type)
  {
    if (log.isTraceEnabled()) {
      log.trace("JsonTypeHandler(" + type + ")");
    }
    if (type == null) {
      throw new IllegalArgumentException("Type argument cannot be null");
    }
    this.type = type;
  }
  
  private T parse(String json)
  {
    try
    {
      if ((json == null) || (json.length() == 0)) {
        return null;
      }
      return (T)objectMapper.readValue(json, this.type);
    }
    catch (IOException e)
    {
      throw new RuntimeException(e);
    }
  }
  
  private String toJsonString(Object obj)
  {
    try
    {
      return objectMapper.writeValueAsString(obj);
    }
    catch (JsonProcessingException e)
    {
      throw new RuntimeException(e);
    }
  }
  
  public T getNullableResult(ResultSet rs, String columnName)
    throws SQLException
  {
    return (T)parse(rs.getString(columnName));
  }
  
  public T getNullableResult(ResultSet rs, int columnIndex)
    throws SQLException
  {
    return (T)parse(rs.getString(columnIndex));
  }
  
  public T getNullableResult(CallableStatement cs, int columnIndex)
    throws SQLException
  {
    return (T)parse(cs.getString(columnIndex));
  }
  
  public void setNonNullParameter(PreparedStatement ps, int columnIndex, T parameter, JdbcType jdbcType)
    throws SQLException
  {
    ps.setString(columnIndex, toJsonString(parameter));
  }
}


/* Location:              E:\360MoveData\Users\admin\Desktop\teacher_wap-0.0.1-SNAPSHOT.jar!\BOOT-INF\classes\com\ruime\\util\JsonTypeHandler.class
 * Java compiler version: 8 (52.0)
 * JD-Core Version:       0.7.1
 */